"""
验证策略命名一致性
检查：策略文件名、类名、strategy_name、runner 文件名是否一致
"""
import os
import re
import sys

def extract_strategy_info(file_path):
    """从策略文件中提取类名和 strategy_name"""
    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read()
    
    # 提取类名
    class_match = re.search(r'class\s+(\w+)\(.*BaseStrategy.*\):', content)
    class_name = class_match.group(1) if class_match else None
    
    # 提取 strategy_name
    strategy_name_match = re.search(r'strategy_name\s*=\s*["\']([^"\']+)["\']', content)
    strategy_name = strategy_name_match.group(1) if strategy_name_match else None
    
    return class_name, strategy_name


def verify_naming():
    """验证命名一致性"""
    print("=" * 80)
    print("策略命名一致性验证")
    print("=" * 80)
    
    strategies_dir = 'trading_system/strategies'
    backtest_dir = 'trading_system/backtest'
    
    issues = []
    verified = []
    
    # 遍历策略文件
    for file in os.listdir(strategies_dir):
        if file.endswith('_strategy.py') and file != 'base_strategy.py':
            file_path = os.path.join(strategies_dir, file)
            
            # 从文件名提取预期的 strategy_name
            expected_name = file.replace('_strategy.py', '')
            
            # 提取实际的类名和 strategy_name
            class_name, actual_strategy_name = extract_strategy_info(file_path)
            
            # 检查 runner 文件是否存在
            runner_file = f'runner_{expected_name}.py'
            runner_path = os.path.join(backtest_dir, runner_file)
            has_runner = os.path.exists(runner_path)
            
            # 验证
            status = "✅"
            problems = []
            
            if actual_strategy_name != expected_name:
                status = "❌"
                problems.append(f"strategy_name 不匹配: 期望 '{expected_name}', 实际 '{actual_strategy_name}'")
            
            if not has_runner:
                status = "⚠️"
                problems.append(f"缺少 runner 文件: {runner_file}")
            
            result = {
                'status': status,
                'file': file,
                'class_name': class_name,
                'strategy_name': actual_strategy_name,
                'expected_name': expected_name,
                'has_runner': has_runner,
                'problems': problems
            }
            
            if problems:
                issues.append(result)
            else:
                verified.append(result)
    
    # 打印结果
    print("\n✅ 验证通过的策略:")
    print("-" * 80)
    for r in verified:
        print(f"  {r['file']:40s} -> {r['strategy_name']:30s} [Runner: {'✓' if r['has_runner'] else '✗'}]")
    
    if issues:
        print("\n\n❌ 发现问题:")
        print("-" * 80)
        for r in issues:
            print(f"\n{r['status']} {r['file']}")
            print(f"   类名: {r['class_name']}")
            print(f"   strategy_name: {r['strategy_name']}")
            print(f"   期望名称: {r['expected_name']}")
            for problem in r['problems']:
                print(f"   ⚠️  {problem}")
    
    print("\n" + "=" * 80)
    print(f"总计: {len(verified)} 个通过, {len(issues)} 个有问题")
    print("=" * 80)
    
    return len(issues) == 0


if __name__ == '__main__':
    success = verify_naming()
    sys.exit(0 if success else 1)
